package com.qfedu.firstpage.filter;

import com.alibaba.fastjson.JSON;
import com.qfedu.firstpage.config.ApplicationHolder;
import com.qfedu.firstpage.config.cache.exception.ExceptionDict;
import com.qfedu.firstpage.config.cache.exception.SystemParams;
import com.qfedu.firstpage.config.cache.service.CacheService;
import com.qfedu.firstpage.entity.ResponseData;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 登录鉴权
 */
public class TokenFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取token
        String token = request.getParameter("token");

        System.out.println("token:" + token);

        if (token != null) {
            // 解密token
            Claims body = Jwts.parser().setSigningKey("FireFly".getBytes()).parseClaimsJws(token).getBody();
            String subject = body.getSubject();
            String uphone = (String) body.get("uphone"); // 获取token中保存的uphone信息

            // 获取RedisTemplate
            CacheService cacheService = ApplicationHolder.getApplicationContext().getBean(CacheService.class);

            // 从redis中获取登录时存入的token
            String fromRedis = cacheService.getFromRedis(SystemParams.JWT_TOKEN_REDIS_PRE + uphone);

            // 判断token是否相等
            if (token.equals(fromRedis)) {
                // token相等 可以放行
                return true;
            } else {
                // 拦截
                response.setContentType("application/json;charset=utf-8");

                ResponseData<Object> responseData = new ResponseData<>();

                responseData.setMessage("尚未登录认证");
                responseData.setMessage(ExceptionDict.UNLOGIN);

                response.getWriter().println(JSON.toJSONString(responseData)); // 将json数据写回页面

                return false; // 拦截
            }

        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
